﻿using Microsoft.IdentityModel.Tokens;
using System;
using System.Collections.Generic;
using System.IdentityModel.Tokens.Jwt;
using System.Security.Claims;
using System.Text;

namespace NewsSevicer
{
    public  class SignSendJWTToken
    {
        // Secret 密钥 (用于签名和验证)
        //public const string SecretKey = "ThisIsASufficientlyLongAndSecureKey12345"; // 替换为自己的密钥
        //public const string Issuer = "xiaoweiWebsite"; // 发行者
        //public const string Audience = "OnlineUsers"; // 受众
        private readonly JwtSettings _jwtSettings;

        // 通过构造函数注入 JwtSettings
        public SignSendJWTToken(JwtSettings jwtSettings)
        {
            _jwtSettings = jwtSettings;
        }
        /// <summary>
        /// 生成 JWT Token
        /// </summary>
        /// <returns>JWT Token 字符串</returns>
        public  string GenerateJwtToken(string EmailAndUserName)
        {
            var securityKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_jwtSettings.SecretKey));
            var credentials = new SigningCredentials(securityKey, SecurityAlgorithms.HmacSha256);

            // 定义 Claims (携带的信息)
            var claims = new[]
            {
            new Claim(JwtRegisteredClaimNames.Sub, "wuwei"),
            new Claim("userId",EmailAndUserName ),
            new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString()) // Token 唯一标识
        };

            // 创建 Token
            var token = new JwtSecurityToken(
                issuer: _jwtSettings.Issuer,
                audience: _jwtSettings.Audience,
                claims: claims,
                expires: DateTime.UtcNow.AddDays(1), // Token 过期时间
                signingCredentials: credentials
            );

            // 返回序列化的 Token
            return new JwtSecurityTokenHandler().WriteToken(token);
        }

        /// <summary>
        /// 验证 JWT Token
        /// </summary>
        /// <param name="token">JWT Token 字符串</param>
        /// <returns>验证通过的 ClaimsPrincipal 或 null</returns>
        public  ClaimsPrincipal ValidateJwtToken(string token)
        {
            try
            {
                var tokenHandler = new JwtSecurityTokenHandler();
                var securityKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_jwtSettings.SecretKey));

                // 验证参数
                var validationParameters = new TokenValidationParameters
                {
                    ValidateIssuer = true, // 验证 Issuer
                    ValidIssuer = _jwtSettings.Issuer,
                    ValidateAudience = true, // 验证 Audience
                    ValidAudience = _jwtSettings.Audience,
                    ValidateLifetime = true, // 验证过期时间
                    IssuerSigningKey = securityKey, // 签名密钥
                    ValidateIssuerSigningKey = true // 验证签名密钥
                };

                // 验证 Token
                var principal = tokenHandler.ValidateToken(token, validationParameters, out _);
                return principal;
            }
            catch (Exception ex)
            {
                Console.WriteLine($"Token validation failed: {ex.Message}");
                return null;
            }
        }
    }
}
